package fileUtils

import (
	"fmt"
	"log"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"strings"
	"utilsx/tools/logUtils"
)

func CreatIfNotExist(fullPath string) bool {
	if FileDirExist(fullPath) {
		logUtils.LogPrintln(3, "File/Dir IsExist :", fullPath)
		return false
	} else {
		err := os.MkdirAll(fullPath, os.ModePerm)
		if err != nil {
			logUtils.LogPrintln(1, "Create File/Dir Error :", fullPath)
			return false
		}
		logUtils.LogPrintln(2, "Create File/Dir Success :", fullPath)
		return true
	}

}

//func FileDirExist(fullPath string) bool {
//	_, err := os.Stat(fullPath)
//	if err != nil && os.IsNotExist(err) {
//		return false
//	}
//	return true
//}

func FileDirExist(fname string) bool {
	info, err := os.Stat(fname)
	if os.IsNotExist(err) {
		return false
	}
	return !info.IsDir()
}

func GetExePath() string {
	ex, err := os.Executable()
	fmt.Println(ex)
	if err != nil {
		logUtils.LogPrintln(1, "获取当前项目路徑失败")
		return ""
	}
	exPath := filepath.Dir(ex)
	return exPath
}

func GetProjectPath() string {
	cwd, _ := os.Getwd()
	return cwd
}

// 最终方案-全兼容
func GetCurrentAbPath() string {
	dir := GetAbPathByExecutable()
	if strings.Contains(dir, GetTmpDir()) {
		return GetAbPathByCaller()
	}
	return dir
}

// 获取系统临时目录，兼容go run
func GetTmpDir() string {
	dir := os.Getenv("TEMP")
	if dir == "" {
		dir = os.Getenv("TMP")
	}
	res, _ := filepath.EvalSymlinks(dir)
	return res
}

// 获取当前执行文件绝对路径
func GetAbPathByExecutable() string {
	exePath, err := os.Executable()
	if err != nil {
		log.Fatal(err)
	}
	res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
	return res
}

// 获取当前执行文件绝对路径（go run）
func GetAbPathByCaller() string {
	var abPath string
	_, filename, _, ok := runtime.Caller(0)
	if ok {
		abPath = path.Dir(filename)
	}
	return abPath
}
